package com.kundi.dooradmin.service;

import com.kundi.dooradmin.entity.User;
import com.kundi.dooradmin.dao.UserDao;
import com.kundi.dooradmin.mapper.UserMapper;
import com.kundi.dooradmin.util.MapUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class UserService {
    @Resource
    UserDao userDao;

    @Resource
    UserMapper userMapper;

    /**
     * 插入用户
     * @param user
     * @return
     */
    public User insert(User user) {
        return userDao.save(user);
    }

    /**
     * 根据用户名获取用户的ID
     * @param username
     * @return
     */
    public Integer getIdByUsername( String username) {
        return userDao.getIdByUsername(username).get(0);
    }

    /**
     * 通过ID获取用户
     * @param id
     * @return
     */
    public User getUserById(Integer id) {
        Optional<User> optionalUser = userDao.findById(id);
        return optionalUser.get();
    }

    /**
     * 获取所有的用户
     * @return
     */
    public List<User> getAllUser() {
        return userDao.getAllUser();
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    public Integer update(User user) {
        // 使用的是mybatis第三方插件mapper，这样可以实现选择性更新，而不会触发数据库的空值报错
        return userMapper.updateByPrimaryKeySelective(user);
    }


    public Map<String, String> login(String username, String password) {
        List<User> users = userMapper.hasUsername(username);
        if(users.size() > 0) {
            User user = users.get(0);
            if(user.getPassword().equals(password)) {
                return MapUtil.responseMap("登录成功", "true");
            } else {
                return MapUtil.responseMap("密码错误", "false");
            }
        } else {
            return MapUtil.responseMap("用户不存在", "false");
        }
    }
}
